<template>
  <div>
    <div :id="canvasId"></div>
    <img
      v-if="props.src"
      draggable="false"
      :style="{
        width: displayWidth,
        height: displayHeight
      }"
      :src="props.src"
      alt=""
    />
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, watchEffect } from 'vue'
import renderSignet from './render'

const props = defineProps({
  src: {
    type: String
  },
  id: {
    type: String
  },
  idPrefix: {
    type: String,
    default: 'signet_canvas_'
  },
  displayWidth: {
    type: String,
    default: '160px'
  },
  displayHeight: {
    type: String,
    default: '160px'
  },
  canvasWidth: {
    type: Number,
    default: 160
  },
  canvasHeight: {
    type: Number,
    default: 160
  },
  color: {
    type: String,
    default: '#ff0000'
  },
  companyName: {
    type: String,
    default: ''
  },
  bottomText: String,
  showStar: Boolean
})

const emit = defineEmits(['update:src'])

let canvas: any = null
let context: any = null

//canvasId
const canvasId = computed(() => {
  return props.idPrefix + props.id
})

// 清除画布
const reset = () => {
  if (canvas && context) {
    context.clearRect(0, 0, canvas.canvasWidth, canvas.canvasHeight)
    canvas.remove()
  }
}
// 初始化画布
const generateImg = () => canvas.toDataURL('image/png', 1)

const init = () => {
  const { companyName, bottomText, showStar, color, canvasWidth, canvasHeight } = props
  nextTick(() => {
    canvas = document.createElement('canvas')
    canvas.width = canvasWidth
    canvas.height = canvasHeight
    context = canvas.getContext('2d')
    context.fillStyle = 'rgba(255, 255, 255, 0)'
    context.fillRect(0, 0, canvas.width, canvas.height)

    renderSignet({
      canvas,
      context,
      companyName,
      bottomText,
      showStar,
      color
    })
    const base64Image = generateImg()
    emit('update:src', base64Image)
    // const container = document.getElementById(canvasId.value)
    // container.appendChild(canvas)
  })
}

watchEffect(() => {
  reset()
  init()
})

defineExpose({
  generateImg
})
</script>
